package com.mobile.common.util;

import java.security.MessageDigest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hyperic.sigar.CpuInfo;
import org.hyperic.sigar.NetFlags;
import org.hyperic.sigar.NetInterfaceConfig;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;


public class StringUtil {

	private static Log log = LogFactory.getLog(StringUtil.class);
	/**
	 * 生成MD5字符串
	 * @param text
	 * @return
	 */
	public static String Md5(String text){
		StringBuilder sb = new StringBuilder();
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] b = md.digest(text.getBytes("utf-8"));
			for(int i=0;i<b.length;i++){
				if(b[i]<0)
					sb.append(b[i]&0xff);
				else if(b[i]<16){
					sb.append("0");
					sb.append(Integer.toHexString(b[i]));
				}else
					sb.append(Integer.toHexString(b[i]));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
	
	/**
	 * 获取CPU硬件信息
	 * @return String CPU信息(CPU生产商:CPU类别#CPU生产商:CPU类别...)
	 */
	public static String getCpusInfo(){
		StringBuilder sbr = new StringBuilder();
		Sigar sigar = new Sigar();
		try {
			CpuInfo[] cpuInfos = sigar.getCpuInfoList();
			for (int i = 0; i < cpuInfos.length; i++) {
				sbr.append(cpuInfos[i].getVendor()); // CPU生产商
				sbr.append(":" + cpuInfos[i].getModel()); // CPU类别
				if (i < cpuInfos.length - 1)
					sbr.append("#");
			}
		} catch (SigarException e) {
			log.error("--获取Cpu失败！", e);
		}
		return sbr.toString();
	}
	
	/**
	 * 获取所有网卡信息
	 * @return String MAC地址(MAC#MAC...)
	 */
	public static String getNetInfo(){
		StringBuilder sbr = new StringBuilder();
		Sigar sigar = new Sigar();
		try {
			String[] ifaces = sigar.getNetInterfaceList();
			for(int i=0;i<ifaces.length;i++){
				NetInterfaceConfig cfg = sigar.getNetInterfaceConfig(ifaces[i]);
				if  (NetFlags.LOOPBACK_ADDRESS.equals(cfg.getAddress()) || (cfg.getFlags() & NetFlags.IFF_LOOPBACK) != 0
	                    || NetFlags.NULL_HWADDR.equals(cfg.getHwaddr())) {
	                continue ;
	            }
				sbr.append(cfg.getHwaddr()); // MAC地址
				if(i<ifaces.length) sbr.append("#");
			}
		} catch (SigarException e) {
			log.error("--获取网卡MAC信息失败",e);
		}
		return sbr.toString();
	}
}
